package com.lagou.controller;

import com.lagou.pojo.Article;
import com.lagou.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Controller
public class IndexController {

    @Autowired
    private ArticleRepository articleRepository;

    @RequestMapping("/index")
    public String index(HttpServletRequest request, Model model) {

        int pageIndex = 0;
        int pageSize = 3;// 每页显示条数

        String pageIndexStr = request.getParameter("pageIndex");
        if (!StringUtils.isEmpty(pageIndexStr)) {
            pageIndex = Integer.valueOf(pageIndexStr) - 1;
        }
        if(pageIndex < 0) {
            pageIndex = 0;
        }

        Pageable pageable = PageRequest.of(pageIndex, pageSize);

        Page<Article> articlePage = articleRepository.findAll(pageable);

        int totalPages = articlePage.getTotalPages();// 总页数
        if (totalPages > 0) {
            List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages).boxed().collect(Collectors.toList());
            model.addAttribute("pageNumbers", pageNumbers);
        }

        model.addAttribute("articles", articlePage.getContent());

        return "client/index";
    }
}
